import { Button, Space, Collapse, Form, Input, DatePicker, Table, Tag, Pagination, message } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom'
import type { ColumnsType } from 'antd/es/table';
import { WechatFilled,AlipayCircleOutlined,SkypeOutlined} from '@ant-design/icons';
import type { TableRowSelection } from 'antd/es/table/interface';
import './css/OrderList.css'
import { getSelectTime } from '../../../utils/publicFun'
const { Panel } = Collapse;
import { getOrderByState, getOrderByCondition } from '../../../api/OrderApi'

// 接口
interface DataType {
	key: React.Key;
	// orderId: number;//序号
	orderId: number;//订单编号
	orderCreated: string;//创建时间
	userId: string; //用户账号
	itemTotal: number;
	paymentMethod: number; //支付方式
	orderSource: number;//订单来源
	orderState: number; //订单状态
	goodsId:number;//商品id
	// dlr_name: string,//收货人姓名
	// dlr_phone: string,//收货人手机号
	// dlr_zipCode: string,//邮政编码
	// address: string,//收货地址
	// goods_name: string,//商品名称
	// goods_pic: string,//商品图片
	// goods_price: number,//商品单价
	// goods_attribute: string,//商品属性
	// goods_number: number,//商品数量
	// remark: string,//买家备注
	// freight: number,//运费
	// discount: number,//优惠金额
}


export default function OrderList() {

	const [form] = Form.useForm();
	// const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [data, setData] = useState<DataType[]>([])  //所有订单数据
	const [isSelect, SetIsSelect] = useState('all')  //选择的某个状态的订单数据
	const [pageCount,setPageCount]=useState<number>()  //订单条数
	const [pageSize,setPageSize]=useState<number>(2) //每页条数
	const [currentPage,setCurrentPage]=useState<number>(1) //当前第几页
	const [selectState,setSelectState]=useState<number>(10) //当前在哪个状态下
	const navigate = useNavigate()  //路由跳转对象
	// 各种订单状态条数
	const [orderCount0,setOrderCount0]=useState<number>(); 
	const [orderCount1,setOrderCount1]=useState<number>(); 
	const [orderCount2,setOrderCount2]=useState<number>(); 
	const [orderCount3,setOrderCount3]=useState<number>(); 
	const [orderCount4,setOrderCount4]=useState<number>(); 
	const [orderCount5,setOrderCount5]=useState<number>(); 
	const [orderCount6,setOrderCount6]=useState<number>(); 
	const [allOrdercount,setAllOrdercount]=useState<number>(); 



	// 判断该订单式什么订单

	// 表格列属性
	const columns: ColumnsType<DataType> = [
		{
			title: '序号',
			dataIndex: 'orderId',
			width:90,
			render: (_, record) => (
				<Button type="link">GS{record.orderId}</Button>
			),
		},
		{
			title: '订单编号',
			dataIndex: 'orderId',
		},
		{
			title: '创建时间',
			dataIndex: 'orderCreated',
		},
		// {
		// 	title: '用户账号',
		// 	dataIndex: 'userId',
		// },
		{
			title: '订单金额',
			dataIndex: 'itemTotal',
			render: (_, record) => (
				<Space size="middle">
					<Button type="link">{record.itemTotal}</Button>
					{/* 订单金额为商品单价*商品数量+运费-折扣 */}
				</Space >
			),
		},
		{
			title: '支付方式',
			dataIndex: 'paymentMethod',
			render: (_, record) => (

				record.paymentMethod == 1 ?  <Tag icon={<WechatFilled />} color="#55acee">
				微信支付
			  </Tag> : record.orderSource == 2 ? <Tag color="#2db7f5" icon={<AlipayCircleOutlined/>}>支付宝支付</Tag> : 
			  <Tag color="#87d068" icon={<SkypeOutlined />}>其他支付</Tag>
				// </Tag>
			),
		},
		{
			title: '订单来源',
			dataIndex: 'orderSource',
			render: (_, record) => (

				record.orderSource == 1 ? <Tag color="#f50">App订单</Tag> : record.orderSource == 2 ? <Tag color="#2db7f5">PC订单</Tag> : <Tag color="#87d068">小程序订单</Tag>
				// </Tag>
			),
		},
		{
			title: '订单状态',
			dataIndex: 'orderState',
			render: (_, record) => (
				record.orderState == 1 ? '待确认' : record.orderState == 2 ? '未支付' : record.orderState == 3 ? '已支付' : record.orderState == 4 ? '未发货' : record.orderState == 5 ? '已发货' : record.orderState == 6 ? '已签收' : '已关闭'
			),
		},
		{
			title: '操作',
			dataIndex: 'operation',
			render: (_, record) => (
				<Space size="middle">
					<Button className='check add' onClick={() => gotoOrderDetail(record.orderId,record.orderState,record.goodsId)}>查看订单</Button>
				</Space >
			),
		},
	];


	// 多选框
	// const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
	// 	console.log('selectedRowKeys changed: ', newSelectedRowKeys);
	// 	setSelectedRowKeys(newSelectedRowKeys);
	// };

	// 点击查看订单
	const gotoOrderDetail = (orderId: number,status:number,goodsId:number) => {
		// 跳转到对应订单详情页
		navigate('/home/order/orderDetails', { state: {orderId,status,goodsId} })
	}

	// 初始获取所有订单数据
	useEffect(() => {
		// 发起请求，查询所有订单
		getAll()
	}, [])

   // 获取当前状态下的所有数据
		const getAll=()=>{
			//	size:每页多少条数据   pagenum:当前第几页
            getOrderByState({
				pageNum:currentPage,
				size:pageSize,
				state:selectState
			}).then(res=>{
				console.log('所有订单',res);
				
				 setData(res.data.allOrderDtos)	
				 setPageCount(res.data.count)
				//  获取设置各个状态订单的条数
				const { OrderCount0,OrderCount1,OrderCount2,OrderCount3,OrderCount4,OrderCount5,OrderCount6,allOrdercount}=res.data.orderCountMap
				setOrderCount0(OrderCount0)
				setOrderCount1(OrderCount1)
				setOrderCount2(OrderCount2)
				setOrderCount3(OrderCount3)
				setOrderCount4(OrderCount4)
				setOrderCount5(OrderCount5)
				setOrderCount6(OrderCount6)
				setAllOrdercount(allOrdercount)	 	
			}).catch(err=>{
				console.log('err111',err);
				message.error('服务器出错啦~~~')
			})
		}

	// 点击头部按钮选择显示所有订单、代付款、待发货、已发货、已完成、已关闭。。。
	const clickBtns = (type: string,state:number) => {		
		setSelectState(state)
		getOrderByState({
			state:state,
			pageNum:currentPage,
			size:pageSize,
		}).then(res=>{
			console.log('res',res);
			
			setData(res.data.allOrderDtos)
			SetIsSelect(type)
			setPageCount(res.data.count)
		}).catch(err=>{
			console.log('err222',err);
			message.error('服务器出错啦~~~')
		})
	}

	// 点击搜索
	const onFinish =(values: any) => {
		// console.log('搜索内容:', values);
		getOrderByCondition({
			orderCreated:values.submit_time ? getSelectTime(values.submit_time) : values.submit_time, //创建时间
			orderId:Number(values.keyword),
			// orderState:selectState,
			page:1,//当前页
			size:2,//每页多少条
			userPhone:values.addressee//收货人手机号
		}).then(res=>{
			console.log('根据条件查询订单结果res',res);
			// if(res.data.code==200){			
				setPageCount(res.data.count)
				setData(res.data.allOrderDtos);
				if(res.data.allOrderDtos.length>0){
					// 查询出有数据
					message.success('查询订单成功~~')
				}else{
					// 没有数据
					// message.info(res.msg)
					message.info('没有你需要的数据~~')
				}
			// }	
		}).catch(err=>{
			console.log('搜索出错err',err);
			message.error('服务器错误~~~')
		})
	};

	// 搜索重置
	const resetHandle = (event: any) => {
		// 阻止默认事件
		event.preventDefault()
		// 清空搜索框
		form.setFieldsValue({
            keyword:'',
			addressee:'',
			submit_time:''
        })
		// 重置 重新获取数据
		getAll()
	}


	//页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
	const pageChange=(page:number, pageSize:number)=>{
		setPageSize(pageSize)
		setCurrentPage(page)
		getOrderByState({
			state:selectState,
			pageNum:page,
			size:pageSize,
		}).then(res=>{
			setData(res.data.allOrderDtos)
			setPageCount(res.data.count)
			// 设置当前页和每页条数
			setPageSize(pageSize)
			setCurrentPage(page)
		}).catch(err=>{
			console.log('err222',err);
			message.error('服务器出错啦~~~')
		})
	}

	// // 每页条数改变
	// const pageSizeChange=(current:number, size:number)=>{
	// 	console.log('current size',current,size);
	// }



	// 表格多选配置
	// const rowSelection: TableRowSelection<DataType> = {
	// 	selectedRowKeys,
	// 	onChange: onSelectChange,
	// 	selections: [
	// 		Table.SELECTION_ALL,
	// 		Table.SELECTION_INVERT,
	// 		Table.SELECTION_NONE,
	// 		{
	// 			key: 'odd',
	// 			text: 'Select Odd Row',
	// 			onSelect: (changableRowKeys) => {
	// 				let newSelectedRowKeys = [];
	// 				newSelectedRowKeys = changableRowKeys.filter((_, index) => {
	// 					if (index % 2 !== 0) {
	// 						return false;
	// 					}
	// 					return true;
	// 				});
	// 				setSelectedRowKeys(newSelectedRowKeys);
	// 			},
	// 		},
	// 		{
	// 			key: 'even',
	// 			text: 'Select Even Row',
	// 			onSelect: (changableRowKeys) => {
	// 				let newSelectedRowKeys = [];
	// 				newSelectedRowKeys = changableRowKeys.filter((_, index) => {
	// 					if (index % 2 !== 0) {
	// 						return true;
	// 					}
	// 					return false;
	// 				});
	// 				setSelectedRowKeys(newSelectedRowKeys);
	// 			},
	// 		},
	// 	],
	// };
	return (
		<div className='orderlist'>
			<p className='head'>订单列表</p>
			{/* 顶部按钮 */}
			<Space wrap className='btns'>
				<Button className={isSelect =='all' ? 'selectBtn' :''}  onClick={() => clickBtns('all',10)}>全部订单({allOrdercount})</Button>
				<Button className={isSelect =='waitConfirm' ? 'selectBtn' :''} onClick={() => clickBtns('waitConfirm',1)}>待确认({orderCount1})</Button>
				<Button className={isSelect =='waitPay' ? 'selectBtn' :''} onClick={() => clickBtns('waitPay',2)}>未支付({orderCount2})</Button>
				<Button className={isSelect =='payFinish' ? 'selectBtn' :''} onClick={() => clickBtns('payFinish',3)}>已支付({orderCount3})</Button>
				<Button className={isSelect =='waitDeliver' ? 'selectBtn' :''} onClick={() => clickBtns('waitDeliver',4)}>未发货({orderCount4})</Button>
				<Button className={isSelect =='deliverFinish' ? 'selectBtn' :''} onClick={() => clickBtns('deliverFinish',5)}>已发货({orderCount6})</Button>
				<Button className={isSelect =='signFinish' ? 'selectBtn' :''} onClick={() => clickBtns('signFinish',6)}>已签收({orderCount5})</Button>
				<Button className={isSelect =='close' ? 'selectBtn' :''} onClick={() => clickBtns('close',0)}>已关闭({orderCount0})</Button>
			</Space>
			{/* 筛选查询 收起 */}
			<div className='search_box'>
				<Collapse defaultActiveKey={['1']}>
					<Panel header="筛选查询" key="1">
						{/* 搜索表单 */}
						<Form form={form} name="horizontal_login" layout="inline" onFinish={onFinish}>
							<Form.Item
								label="关键词"
								name="keyword"
								// rules={[{ required: true, message: '请输入搜索关键词' }]}
							>
								<Input placeholder="订单号/商品货号" allowClear/>
							</Form.Item>
							<Form.Item
								label="收货人"
								name="addressee"
								// rules={[{ required: true, message: '请输入收货人信息' }]}
							>
								<Input
									placeholder="用户昵称/手机号" allowClear
								/>
							</Form.Item>
							<Form.Item
								label="提交时间"
								name="submit_time"
								// rules={[{ required: true, message: '请输入订单提交时间' }]}
							>
								<DatePicker showTime placeholder="请选择时间" size='small' allowClear/>
							</Form.Item>
							<Form.Item shouldUpdate>
								{() => (
									<Space wrap>
										<Button
											type="primary"
											htmlType="submit"
										>
											查询
										</Button>
										<Button htmlType="button" className='orderlist_reset' onClick={resetHandle}>
											重置
										</Button>
									</Space>
								)}
							</Form.Item>
						</Form>
					</Panel>
				</Collapse>
			</div>
			{/* 表格内容  rowSelection={rowSelection}*/} 
			<Table rowKey={(item)=>item.orderCreated} className='order_table'  columns={columns} dataSource={data} bordered={true} 
			  pagination={{
				position:['bottomCenter'],
				total:pageCount,
				defaultPageSize:pageSize,
				defaultCurrent:currentPage,
				pageSizeOptions:[2,3,5],
				showSizeChanger:true,
				showQuickJumper:true,
				onChange:pageChange,
				showTotal:(total:number) => `共有 ${total} 条数据`
			  }}
			/>
			{/* 分页 */}
			{/* <Pagination
			    onChange={pageChange}
				onShowSizeChange={pageSizeChange}
			    className='pagination'
				total={pageCount}
				showSizeChanger
				showQuickJumper
				defaultPageSize={2}
				defaultCurrent={1}
				pageSizeOptions={['2','3','5']}
				// pageSizeOptions=['5','10','15','20']
				showTotal={(total:number) => `共有 ${total} 条数据`}
			/> */}
    </div>
  )
}